<template>
  <div class="box">
    <div class="card-container">
      <div class="flex_box" :style="`flex:${projectBox ? '1' : '0.1'};`">
        <div v-if="projectBox" class="head">
          <el-input v-model="projectName" placeholder="请输入项目名称" clearable size="small"
            prefix-icon="el-icon-search" style="margin-bottom: 20px" />
        </div>
        <div v-if="projectBox" class="content">
          <ul v-if="projectOptions.length > 0">
            <li @mouseenter="hovrEvent" @mouseleave="hoverText = false"
              :style="`background: ${i.projectId == projectId ? 'rgba(230, 247, 255, 1);' : ''}`"
              @click="clickProject(i)" v-for="i in projectOptions" :key="i.projectId">
              <span>{{i.shortName}}</span>
            </li>
          </ul>
          <el-empty v-else description="暂无数据"></el-empty>
        </div>
        <div @click="projectBoxFun" class="divIcon">
          <i v-if="projectBox" class="el-icon-caret-left"></i>
          <i v-else class="el-icon-caret-right"></i>
        </div>

      </div>

      <div class="flex_box" :style="`flex:${deviceBox ? '1' : '0.1'};`">
        <div v-if="deviceBox" class="head">
          <el-input v-model="deviceName" placeholder="请输入设备序列号" clearable size="small"
            prefix-icon="el-icon-search" style="margin-bottom: 20px" />
        </div>
        <div v-if="deviceBox" class="content">
          <ul v-if="deviceOptions.length > 0">
            <li @mouseenter="hovrEvent" @mouseleave="hoverText = false"
              :style="`background: ${i.deviceCode == deviceCode ? 'rgba(230, 247, 255, 1);' : ''}`"
              @click="clickDevice(i)" v-for="i in deviceOptions" :key="i.deviceCode">
              <span>{{i.deviceCode}}</span>
            </li>
          </ul>
          <el-empty v-else description="暂无数据"></el-empty>
        </div>
        <div @click="deviceBoxFun" class="divIcon">
          <i v-if="deviceBox" class="el-icon-caret-left"></i>
          <i v-else class="el-icon-caret-right"></i>
        </div>
      </div>
      <div v-if="deviceOptions.length > 0" style="flex:4;width: 0;" class="rigthBox"
        @scroll="onScroll">
        <el-row style="padding: 20px 20px 0 20px;" :gutter="10">
          <el-col :span="16" :offset="0">
            <div class="header-title">{{deviceInfo.siteName}}</div>
          </el-col>
          <el-col :span="8" :offset="0">
            <div class="header-coord">北纬N：{{deviceInfo.latitude}}° 东经E：{{deviceInfo.longitude}}°
            </div>
          </el-col>
          <el-col :span="8" :offset="0">
            <div class="label-text">
              <div>软件版本:</div>
              <div>{{deviceInfo.softwareVersion}}</div>
            </div>
          </el-col>
          <el-col :span="8" :offset="0">
            <div class="label-text">
              <div>设备类型:</div>
              <div>{{deviceInfo.deviceTypeLabel}}</div>
            </div>
          </el-col>
          <el-col :span="8" :offset="0">
            <div class="label-text">
              <div>设备序列号:</div>
              <div>{{deviceInfo.deviceCode}}</div>
            </div>
          </el-col>
          <!-- <el-col :span="8" :offset="0">
            <div class="label-text">
              <div>设备厂商:</div>
              <div>{{deviceInfo.facCode}}</div>
            </div>
          </el-col> -->
          <el-col :span="8" :offset="0">
            <div class="label-text">
              <div>所属项目:</div>
              <div>{{deviceInfo.projectName}}</div>
            </div>
          </el-col>
          <el-col :span="8" :offset="0">
            <div class="label-text">
              <div>设备型号:</div>
              <div>{{deviceInfo.model}}</div>
            </div>
          </el-col>
          <el-col :span="24" :offset="0">
            <div class="label-text">
              <div>地址:</div>
              <!-- <div>{{deviceInfo.address}}</div> -->
              <div>{{$getAddress(deviceInfo.deviceAddress,areaList)}} {{deviceInfo.address}}</div>
            </div>
          </el-col>
        </el-row>
        <el-divider></el-divider>
        <div class="tab" ref="tab">
          <div v-for="(item,index) in tabs" :key="item.refName"
            :class="tabName == item.refName ? 'true' : ''" @click="jump(item,index)">
            {{item.name}}
          </div>
        </div>
        <div class="componentsBox" :ref="tabs[0].refName">
          <operation-rate ref="operationRate" :deviceCode="deviceCode" />
        </div>
        <!-- <el-divider></el-divider>
        <div class="componentsBox" :ref="tabs[1].refName">
          <eew ref="eew" :deviceCode="deviceCode" />
        </div>
        <el-divider></el-divider>
        <div class="componentsBox" :ref="tabs[2].refName">
          <warning ref="warning" :deviceCode="deviceCode" />
        </div> -->
      </div>
      <div v-else style="flex:4;width: 0;">
        <el-empty description="暂无数据"></el-empty>
      </div>
    </div>
    <div class="hover-text" ref="hoverText" v-show="hoverText"></div>
  </div>
</template>

<script>
import operationRate from './operationRate.vue';
import eew from './eew.vue';
import warning from './warning.vue';
import {
  getProject,
  getDevice,
  getDeviceInfo,
} from '@/api/runningLog/runningLog.js';
export default {
  name: 'runningLog',
  components: { operationRate, eew, warning },
  data() {
    return {
      setTime: null,
      projectBox: true,
      deviceBox: true,
      hoverText: false,
      projectId: null,
      projectName: '',
      projectOptions: [],
      projectOptions1: [],
      deviceOptions: [],
      deviceOptions1: [],
      deviceCode: null,
      deviceName: '',
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      tabIndex: '0',
      tabName: 'setOneRef',
      tabs: [
        {
          name: '运行率',
          refName: 'setOneRef',
        },
        // {
        //   name: '地震预警',
        //   refName: 'setTwoRef',
        // },
        // {
        //   name: '地震速报',
        //   refName: 'setThreeRef',
        // },
      ],
      deviceInfo: {
        address: '--',
        softwareVersion: '--',
        deviceTypeLabel: '--',
        deviceCode: '--',
        facCode: '--',
        modelTypeLabel: '--',
        projectName: '--',
        siteName: '--',
        latitude: '0',
        longitude: '0',
      },
      areaList: [],
    };
  },
  computed: {},
  created() {
    // if (process.client){}
  },
  mounted() {
    // this.hovrEvent();
    this.init();
  },
  activated() {
    this.init();
  },
  beforeCreate() {},
  beforeMount() {},
  watch: {
    projectName(newVal, oldVal) {
      this.projectOptions = this.projectOptions1.filter(
        (item) => item.shortName.indexOf(newVal) !== -1
      );
    },
    deviceName(newVal, oldVal) {
      this.deviceOptions = this.deviceOptions1.filter(
        (item) => item.deviceCode.indexOf(newVal) !== -1
      );
    },
  },
  methods: {
    deviceBoxFun() {
      this.deviceBox = !this.deviceBox;
      // this.$refs.operationRate
      // this.$nextTick(() => {
      //   this.$refs.operationRate.init();
      //   this.$refs.eew.init();
      //   this.$refs.warning.init();
      // });
      const _this = this;
      clearTimeout(this.setTime);
      this.setTime = setTimeout(() => {
        _this.$refs.operationRate.init();
        _this.$refs.eew.init();
        _this.$refs.warning.init();
      }, 350);
    },
    projectBoxFun() {
      this.projectBox = !this.projectBox;
      // this.$nextTick(() => {
      //   this.$refs.operationRate.init();
      //   this.$refs.eew.init();
      //   this.$refs.warning.init();
      // });
      const _this = this;
      clearTimeout(this.setTime);
      this.setTime = setTimeout(() => {
        _this.$refs.operationRate.init();
        _this.$refs.eew.init();
        _this.$refs.warning.init();
      }, 350);
    },
    async init() {
      this.areaList = await this.$api.getAreaList();
      this.handelProject();
    },
    async handelProject() {
      const res = await getProject();
      if (res.code == 200) {
        this.projectOptions = res.data;
        this.projectOptions1 = res.data;
        this.projectId = this.projectOptions[0].projectId;
        this.handelDevice();
      }
    },
    async handelDevice() {
      const res = await getDevice(this.projectId);
      if (res.code == 200) {
        this.deviceOptions = res.data;
        this.deviceOptions1 = res.data;
        if (this.deviceOptions.length > 0) {
          this.deviceCode = this.deviceOptions[0].deviceCode;
          this.handelDeviceInfo();
        }

        // this.$nextTick(() => {
        //   this.$refs.operationRate.getList();
        //   this.$refs.operationRate.init();
        // });
      }
    },
    async handelDeviceInfo() {
      const res = await getDeviceInfo({ deviceCode: this.deviceCode });
      if (res.code == 200) {
        this.deviceInfo = res.data;
      }
    },
    clickDevice(item) {
      this.deviceCode = item.deviceCode;
      this.handelDeviceInfo();
      // this.$refs.operationRate.getList();
      // this.$refs.operationRate.init();
    },
    clickProject(item) {
      this.projectId = item.projectId;
      this.handelDevice();
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.handleQuery();
    },
    hovrEvent(e) {
      if (
        e.target.children[0].getBoundingClientRect().width <
        e.target.getBoundingClientRect().width
      )
        return;
      if (!this.hoverText) {
        this.hoverText = true;
        this.$nextTick(() => {
          let parent = document.querySelector('.content');
          let dom = this.$refs.hoverText;
          if (dom) {
            dom.innerHTML = e.target.innerHTML;
            dom.style.top = e.target.offsetTop - parent.scrollTop - 25 + 'px';
            dom.style.left =
              e.target.offsetLeft +
              e.target.clientWidth / 2 -
              dom.clientWidth / 2 +
              'px';
          }
        });
      }
    },
    jump(tab, index, event) {
      let target = document.querySelector('.rigthBox');
      let scrollItems = document.querySelectorAll('.componentsBox');
      // 判断滚动条是否滚动到底部
      if (target.scrollHeight <= target.scrollTop + target.clientHeight) {
        // this.tabIndex = tab.index.toString();
        this.tabIndex = index;
      }
      let totalY =
        scrollItems[index].offsetTop - scrollItems[0].offsetTop + 240; // 锚点元素距离其offsetParent(这里是body)顶部的距离(待滚动的距离)
      let distance = document.querySelector('.rigthBox').scrollTop; // 滚动条距离滚动区域顶部的距离
      // let distance = document.body.scrollTop || document.documentElement.scrollTop || window.pageYOffset // 滚动条距离滚动区域顶部的距离(滚动区域为窗口)
      // 滚动动画实现, 使用setTimeout的递归实现平滑滚动，将距离细分为50小段，10ms滚动一次
      // 计算每一小段的距离
      let step = totalY / 50;
      if (totalY > distance) {
        smoothDown(document.querySelector('.rigthBox'));
      } else {
        let newTotal = distance - totalY;
        step = newTotal / 50;
        smoothUp(document.querySelector('.rigthBox'));
      }

      // 参数element为滚动区域
      function smoothDown(element) {
        console.log('distance:', distance);
        console.log('totalY:', totalY);
        if (distance < totalY) {
          distance += step;
          element.scrollTop = distance;
          setTimeout(smoothDown.bind(this, element), 10);
        } else {
          element.scrollTop = totalY;
        }
      }

      // 参数element为滚动区域
      function smoothUp(element) {
        if (distance > totalY) {
          distance -= step;
          element.scrollTop = distance;
          setTimeout(smoothUp.bind(this, element), 10);
        } else {
          element.scrollTop = totalY;
        }
      }
    },
    // 滚动条滚动
    onScroll(e) {
      let scrollItems = document.querySelectorAll('.componentsBox');
      for (let i = scrollItems.length - 1; i >= 0; i--) {
        // 判断滚动条滚动距离是否大于当前滚动项可滚动距离
        let judge =
          e.target.scrollTop >=
          scrollItems[i].offsetTop - scrollItems[0].offsetTop - 100;
        if (judge) {
          this.tabIndex = i.toString();
          // 找对应的tab-name值
          this.tabName = this.tabs[this.tabIndex].refName;
          break;
        }
      }
    },
  },
};
</script>
<style lang='scss' scoped>
::v-deep .el-divider--horizontal {
  margin: 12px 0;
}
.box {
  width: 100%;
  height: 100%;
  padding: 16px;
  position: relative;
}
.divIcon {
  position: absolute;
  padding: 5px;
  padding-right: 0;
  right: 0px;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  border: 1px solid #ccc;
  border-top-left-radius: 5px;
  border-bottom-left-radius: 5px;
  border-right: none;
}
.header {
  padding: 12px 12px 0 12px;
  // height: 64px;
  background: #ffffff;
  border-radius: 12px;
}
.card-container {
  display: flex;
}
.hover-text {
  position: absolute;
  background: #303133;
  color: #fff;
  border-radius: 4px;
  padding: 10px;
  z-index: 2000;
  font-size: 12px;
  line-height: 1.2;
  min-width: 10px;
  word-wrap: break-word;
  pointer-events: none;
}
.flex_box {
  position: relative;
  flex: 1;
  border-right: 1px solid rgba(0, 0, 0, 0.1);
  width: 0;
  display: flex;
  flex-direction: column;
  transition: flex 0.3s linear;
}
.head,
.content {
  padding: 10px 20px 0 20px;
}
.content {
  flex: 1;
}
.content,
.rigthBox {
  overflow: hidden;
  overflow-y: auto;
  &::-webkit-scrollbar {
    width: 8px;
    /*height: 4px;*/
  }
  &::-webkit-scrollbar-thumb {
    border-radius: 4px;
    -webkit-box-shadow: inset 0 0 5px rgba(217, 217, 217, 1);
    background: rgba(0, 0, 0, 0.2);
  }
  &::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 5px rgba(240, 240, 240, 1);
    border-radius: 4px;
    background: rgba(0, 0, 0, 0.1);
  }
}
ul {
  margin: 0;
  padding: 0;
  height: 100%;
  cursor: pointer;
  li {
    list-style: none;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
    height: 50px;
    line-height: 50px;
    border-top: 1px solid rgba(0, 0, 0, 0.1);
    text-align: center;
    &:hover {
      background: rgba(230, 247, 255, 1);
    }
  }
}
.header-title {
  font-size: 16px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: bold;
  color: #000000;
}
.header-coord {
  box-sizing: border-box;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
  &::before {
    content: ' ';
    display: inline-block;
    width: 18px;
    height: 18px;
    background: url('../../assets/images/location.png') no-repeat center center;
    transform: translateY(10%);
    padding: 0 15px;
  }
}
.label-text {
  display: flex;
  width: 100%;
  padding: 12px 0;
  > div:nth-child(1) {
    // min-width: 100px;
    padding-right: 20px;
    height: 22px;
    line-height: 22px;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #595959;
  }
  > div:nth-child(2) {
    height: 22px;
    line-height: 22px;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.85);
  }
}
.tab {
  display: flex;
  margin-left: 24px;
  position: sticky;
  top: 0;
  background: #fff;
  z-index: 999;
  > div {
    margin: 8px 16px 0 0px;
    height: 32px;
    line-height: 32px;
    cursor: pointer;
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.7);
  }
  .true {
    font-size: 16px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: bold;
    color: rgba(0, 0, 0, 0.85);
    border-bottom: 2px solid rgba(24, 144, 255, 1);
  }
}
.componentsBox {
  width: 100%;
  height: 554px;
  box-sizing: border-box;
  padding: 0 20px;
}
</style>